package com.altio.swing;


import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 * Listener that when a mouse drag occurs sets a given component to the bounds
 * dictated by that drag.
 * 
 * @author tomm
 * 
 */
public class DragSelectListener implements MouseMotionListener, MouseListener {
  /** True if the user is currently dragging */
  private boolean dragging;
  /** The point the user dragged from */
  private Point dragPoint = new Point();

  /** Component whose bounds should be set */
  private Component component = null;

  public DragSelectListener(Component component) {
    this.component = component;
  }

  public void mouseDragged(MouseEvent e) {
    if (component != null) {
      Point dragPointB = e.getPoint();
      // Work out the bounds dictated by the drag
      int x = Math.min(dragPoint.x, dragPointB.x);
      int y = Math.min(dragPoint.y, dragPointB.y);
      int w = Math.abs(dragPoint.x - dragPointB.x);
      int h = Math.abs(dragPoint.y - dragPointB.y);
      // Set the bounds of the component
      component.setBounds(x, y, w, h);
    }
  }

  public void mouseMoved(MouseEvent e) {

  }

  public void mouseClicked(MouseEvent e) {

  }

  public void mouseEntered(MouseEvent e) {

  }

  public void mouseExited(MouseEvent e) {

  }

  public void mousePressed(MouseEvent e) {
    // Dragging started
    dragging = true;
    // Dragging started here
    dragPoint = e.getPoint();

    if (component != null) {
      // Move the component
      component.setLocation(dragPoint);
      // Give it zero bounds until the user drags
      component.setSize(0, 0);
      component.setVisible(true);
    }
  }

  public void mouseReleased(MouseEvent e) {
    if (dragging = true) {
      // Consume so it doesn't go to other listeners
      e.consume();
    }
    // Stop dragging
    dragging = false;

    if (component != null) {
      // Hide the component again
      component.setVisible(false);
    }
  }

  public Component getDragComponent() {
    return component;
  }

  public boolean isDragging() {
    return dragging;
  }
}
